package com.example.demo.netty.groupChat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

//自定义一个服务器端业务处理类
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    public static List<Channel> channels = new ArrayList<Channel>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override  //通道就绪
    public void channelActive(ChannelHandlerContext ctx)  {
        Channel inChannel=ctx.channel();
        channels.add(inChannel);
        System.out.println("[Server]:"+inChannel.remoteAddress().toString().substring(1)+"上线");
    }
    @Override  //通道未就绪
    public void channelInactive(ChannelHandlerContext ctx)  {
        Channel inChannel=ctx.channel();
        channels.remove(inChannel);
        System.out.println("[Server]:"+inChannel.remoteAddress().toString().substring(1)+"离线");
    }
    @Override  //读取数据
    protected void channelRead0(ChannelHandlerContext ctx, String s)  {
        try {
            Channel inChannel=ctx.channel();
            System.out.println("服务器接收到消息 时间: [" + sdf.format(new java.util.Date()) + "] -> " + "["+inChannel.remoteAddress().toString().substring(1)+"]"+"发送的消息："+s);
            System.out.println("服务器进行消息转发 ...\n");
            for(Channel channel:channels){
                if(channel!=inChannel){ //排除自己
                    channel.writeAndFlush("["+inChannel.remoteAddress().toString().substring(1)+"]"+"说："+s+"\n");
                }
            }
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}
